﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RFIDStockManagement.BLL;
using RFIDStockManagement.Model.Public;
using RFIDStockManagement.Common.Public.Enums;
using RFIDStockManagement.Common.Public;
using DevExpress.XtraEditors;
using IOReadWriter;

namespace RFIDStockManagement.Client
{
    public partial class SotckCheckForm : XtraUserControl, IStockContainer
    {
        private RfidSpeedwayReader m_RfidReader = null;
        private RfidWriter m_RfidWriter = null;
        private StockCheckManager _thisManager;
        private long _stockId;
        private AddStockCheckSegmentForm _addForm;

        public AddStockCheckSegmentForm AddForm
        {
            get
            {
                if (_addForm == null)
                {
                    _addForm = new AddStockCheckSegmentForm(_thisManager);
                }

                if (_addForm.IsDisposed)
                {
                    _addForm = new AddStockCheckSegmentForm(_thisManager);
                }

                return _addForm;
            }
        }

        public SotckCheckForm()
        {
            InitializeComponent();
            _thisManager = new StockCheckManager();
            InitCheckInfos(-1);
            InitStockList();

        }
        private void SotckCheckForm_Load(object sender, EventArgs e)
        {
            m_RfidWriter = new RfidWriter(this, EnumIOStockOperate.StockCheck);
        }

        private void barAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            StockCheckInfo addInfo = AddForm.AddNewInfoShow();
            if (addInfo.FId > 0)//添加成功
            {
                InitCheckInfos(addInfo.FId);
            }

           
        }

        private void InitCheckInfos(int id)
        {

            combList.Properties.Items.Clear();
            List<StockCheckInfo> checks = _thisManager.GetList(EnumStockCheckStatus.Default);
            int index;

            combList.Properties.BeginUpdate();
            foreach (StockCheckInfo x in checks)
            {
                index = combList.Properties.Items.Add(new ComBoxItem(x.FCaption, x.FId));
                if (x.FId == id)
                {
                    combList.SelectedIndex = index;
                }
            }

            combList.Properties.EndUpdate();
        }
        private void InitStockList()
        {
            DataTable dtStockList = BasicInfoManager.GetList(null, EnumBasicInfo.Stock);

            combStockList.Properties.BeginUpdate();
            foreach (DataRow xx in dtStockList.Rows)
            {
                combStockList.Properties.Items.Add(new ComBoxItem(xx["FName"].ToString(), PublicFunction.NotNullLng(xx["Fid"])));
            }
            combStockList.Properties.EndUpdate();
        }

        private void combList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComBoxItem curInfo;
            StockCheckInfo curCheckInfo;
            curInfo = combList.Properties.Items[combList.SelectedIndex] as ComBoxItem;
            if (curInfo == null)
            {
                bntEnd.Enabled = false;
                bntStart.Enabled = false;
                bntPause.Enabled = false;
                return;
            }

            curCheckInfo = _thisManager.GetStockCheckInfo((int)curInfo.Item);
            if (curCheckInfo == null)
            {
                barStatus.Caption = "当前盘点周期信息不存在或已经被删除";

                bntEnd.Enabled = false;
                bntStart.Enabled = false;
                bntPause.Enabled = false;
                return;
            }

            txtStartTime.Text = curCheckInfo.FStartTime.ToString(PublicConst.LongTimeFormater);
            switch (curCheckInfo.Status)
            {
                case EnumStockCheckStatus.Started:
                case EnumStockCheckStatus.Default:
                    bntEnd.Enabled = true;
                    bntStart.Enabled = true;
                    bntPause.Enabled = false;
                    txtEndTime.Text = string.Empty;
                    txtStatus.Text = "未完成";
                    break;
                case EnumStockCheckStatus.Finished:
                    bntEnd.Enabled = false;
                    bntStart.Enabled = false;
                    bntPause.Enabled = false;
                    txtStatus.Text = "完成";
                    txtEndTime.Text = curCheckInfo.FEndTime.ToString(PublicConst.LongTimeFormater);
                    break;

                default:
                    bntEnd.Enabled = true;
                    bntStart.Enabled = true;
                    bntPause.Enabled = false;
                    txtEndTime.Text = string.Empty;
                    break;
            }

            barStatus.Caption = "完毕";
        }

        private void barDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ComBoxItem curInfo;
            
            string errStr;
            if (combList.Properties.Items.Count <= 0) return;

            curInfo = combList.Properties.Items[combList.SelectedIndex] as ComBoxItem;

            if (curInfo == null) return;


            if (!AlertForm.Confirm("真的要删除:" + curInfo.Caption + ",以及这个盘点周期内的所有信息么?"))
            {
                return;
            }

            if (_thisManager.Delete((int)curInfo.Item, out errStr))
            {
                combList.Properties.Items.RemoveAt(combList.SelectedIndex);
                combList.SelectedItem = null;
                AlertForm.ShowMessage("删除成功!");
                bntEnd.Enabled = false;
                bntStart.Enabled = false;
                bntPause.Enabled = false;
                txtStatus.Text = "";
                txtEndTime.Text = string.Empty;
                txtStartTime.Text = string.Empty;
                return;
                
            }
            else
            {
                AlertForm.ShowError(errStr);
                return;
            }


        }

        private StockCheckDetailsBuilder _builder = null;
        private void bntStart_Click(object sender, EventArgs e)
        {
            long testStockId;
            
            ComBoxItem curInfo;
            StockCheckInfo curCheckInfo;
            curInfo = combList.SelectedItem as ComBoxItem;

            if (curInfo == null) return;

            int fid = (int)curInfo.Item;

            curCheckInfo = _thisManager.GetStockCheckInfo(fid);

            if (curCheckInfo == null)
            {
                AlertForm.ShowError("当前选择的盘点信息未找到,或已被删除!");
                return;
            }

            if (curCheckInfo.Status == EnumStockCheckStatus.Finished)
            {

                AlertForm.ShowError("当前选择的盘点周期已经结束,不能进行盘点!");
                return;
            }

            //仓库信息
            curInfo = combStockList.SelectedItem as ComBoxItem;

            if (curInfo == null)
            {
                AlertForm.ShowError("请选择当前需要盘点的仓库!");
                return;
            }

            testStockId = (long)curInfo.Item;

            _stockId = testStockId;
            
            //开始扫描
            _builder = new StockCheckDetailsBuilder(fid);
            StartReader();
        }

        private void bntPause_Click(object sender, EventArgs e)
        {
            StopReader(false);
            if (_builder != null && _builder.Details.Count > 0)
            {
                _thisManager.SaveCheckDetails(_builder.Fid, _builder.Details);
                _builder.Details.Clear();
            }
        }

        private void StartReader()
        {

            if (m_RfidReader == null)
            {
                string[] readerCfg = SpeedwayPublicFunction.GetStockCheckSpeedwayCfg();
                if (readerCfg == null)
                {
                    AlertForm.ShowMessage("Speedway配置不正确");
                    return;
                }
                m_RfidReader = new RfidSpeedwayReader(readerCfg[0], readerCfg[1], EnumIOStockOperate.StockCheck);
            }
            //这里要禁用开始盘点按钮,和结束盘点按钮
            bntStart.Enabled = false;
            bntEnd.Enabled = false;
            bntPause.Enabled = true;

            m_RfidReader.StartRead();
            m_RfidWriter.StartWrite();
        }
        public void StopReader(bool disConnect)
        {
            if (m_RfidReader != null)
            {
                m_RfidReader.StopRead(disConnect);
            }
            if (m_RfidWriter != null)
            {
                m_RfidWriter.StopWrite();
            }
            //这里要禁用按钮
            bntStart.Enabled = true;
            bntEnd.Enabled = true;
            bntPause.Enabled = false;
            if (disConnect)
            {
                if (_builder != null && _builder.Details.Count > 0)
                {
                    _thisManager.SaveCheckDetails(_builder.Fid, _builder.Details);
                    _builder.Details.Clear();
                }
            }
        }

        #region IStockContainer Member

        public bool IsShowed { get; set; }
        public void ShowRfidData(List<RfidDataInfo> lstResult)
        {
            List<string> lstRfid = new List<string>();
            foreach (RfidDataInfo item in lstResult)
            {
                _builder.AddDetail(item.ItemId, item.Rfid, _stockId, 0, item.UnitId);
                _scanCount++;
            }
            if (_builder != null && _builder.Details.Count >= 500)
            {
                _thisManager.SaveCheckDetails(_builder.Fid, _builder.Details);
                _builder.Details.Clear();
            }

            UpdateDataCountDelegate delegateMothod = new UpdateDataCountDelegate(UpdateDataCountHandler);
            this.Invoke(delegateMothod);
        }
        private delegate void UpdateDataCountDelegate();
        private int _scanCount = 0;
        private void UpdateDataCountHandler()
        {
            try
            {
                lblScanCount.Text = _scanCount.ToString();
            }
            finally
            {
                IsShowed = true;
            }
        }

        #endregion

        private void bntEnd_Click(object sender, EventArgs e)
        {
 

            ComBoxItem curInfo;
            StockCheckInfo curCheckInfo;
            curInfo = combList.SelectedItem as ComBoxItem;

            if (curInfo == null) return;

            int fid = (int)curInfo.Item;

            curCheckInfo = _thisManager.GetStockCheckInfo(fid);

            if (curCheckInfo == null)
            {
                AlertForm.ShowError("当前选择的盘点信息未找到,或已被删除!");
                return;
            }

            if (curCheckInfo.Status == EnumStockCheckStatus.Finished)
            {

                AlertForm.ShowError("当前选择的盘点周期已经结束!");
                return;
            }

            if (_thisManager.SetStatus(curCheckInfo.FId, EnumStockCheckStatus.Finished))
            {

                txtStatus.Text = "完成";

                //先禁用所有按钮
                bntStart.Enabled = false;
                bntPause.Enabled = false;
                bntPause.Enabled = false;
            }
            else
            {
                AlertForm.ShowError("结束当前盘点周期时,产生未知错误!");
                return;
            }

            
        }

    }
}
